//
//  APPLEStatusPictureView.swift
//  123
//
//  Created by pangjiaxing on 16/1/3.
//  Copyright © 2016年 pangjiaxing. All rights reserved.
//

import UIKit
import SDWebImage
import SnapKit


// 配图视图里面最大的列数
let HMStatusPictureMaxCol = 3
// 可重用 id
private let HMStatusPictureCellId = "HMStatusPictureCellId"
// 每一个条目之前的间距
private let itemMargin: CGFloat = 5
// 每一个条目的宽度以及高度
private let itemWH = CGFloat(Int((mainScreenW - 2 * AppleStatusCellMargin - 2 * itemMargin) / CGFloat(HMStatusPictureMaxCol)))




class APPLEStatusPictureView: UICollectionView,UICollectionViewDataSource {
    
    // 作测试用，显示当前配图控件里面要显示多少张图片
    private lazy var countLabel: UILabel = {
        let label = UILabel(textColor: UIColor.blackColor(), fontsize: 35)
        return label
    }()
    
    
    var picUrls:[APPLEStatusPictureInfo]?{
        didSet{
            let count = picUrls?.count ?? 0
            countLabel.text = "\(count)"
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(calcViewSize(count))
            }
            reloadData()
        }
    }
    private func calcViewSize (count:Int) -> CGSize {
        
        if count == 1 {
            // 返回那一图片的大小
            // 从缓存里面取出图片 --> key 就是图片地址
            let key = picUrls!.first!.thumbnail_pic
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            // 判断从缓存里面在否真的能够取出图片
            if image != nil {
                var size = image.size
                
                // 过窄的处理
                if size.width < 80 {
                    
                    let width: CGFloat = 80
                    let height = width / size.width * size.height
                    
                    size.width = width
                    // 约束最大的高度
                    size.height = height > 150 ? 150 : height
                }else if size.width > 200 {
                    // 图片过宽的处理
                    let width: CGFloat = 200
                    let height = width / size.width * size.height
                    
                    size.width = width
                    size.height = height
                }
                
                // 更改 cell 的大小
                let layout = collectionViewLayout as! UICollectionViewFlowLayout
                layout.itemSize = size
                
                return size
            }else {
                // 如果没有取出来，直接返回正方形的 size
                return CGSize(width: itemWH, height: itemWH)
            }
        }else{
            let layout = collectionViewLayout as! UICollectionViewFlowLayout
            layout.itemSize = CGSize(width: itemWH, height: itemWH)
        }
        
        
        // 
        var col = count > HMStatusPictureMaxCol ? HMStatusPictureMaxCol : count
        
        if count == 4{
            col = 2
        }
            
        let row = (count-1) / HMStatusPictureMaxCol + 1
        
        // 计算宽度以及高度
        let width = CGFloat(col) * itemWH + CGFloat(col - 1) * itemMargin
        let height = CGFloat(row) * itemWH + CGFloat(row - 1) * itemMargin
        
        // 返回结果
        return CGSize(width: width, height: height)
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        addSubview(countLabel)
        
        countLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
        
        
        // 设置数据源为自己
        dataSource = self
        // 注册cell
        registerClass(AppleStatusPictureViewCell.self, forCellWithReuseIdentifier: HMStatusPictureCellId)
        
        print(itemWH)
        
        // 比如现在 picture View 的宽度是 205.3333333333233
        // 100
        
        
        // 设置每一个 cell 的大小
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
       
        // 设置间距
        // 列间距
        layout.minimumInteritemSpacing = itemMargin
        // 设置行间距
        layout.minimumLineSpacing = itemMargin
        
        addSubview(countLabel)
        
        countLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
    }
    
    
}

extension APPLEStatusPictureView {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HMStatusPictureCellId, forIndexPath: indexPath) as! AppleStatusPictureViewCell
        cell.picUrl = picUrls![indexPath.item]
        return cell
    }
}


private class AppleStatusPictureViewCell:UICollectionViewCell{
    // MARK: - 懒加载控件
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        imageView.contentMode = .ScaleAspectFill
        // 截取掉超出部分
        imageView.clipsToBounds = true
        return imageView
    }()
    
    
    
    var picUrl:APPLEStatusPictureInfo?{
        didSet{
            if let urlString = picUrl?.thumbnail_pic{
                let url = NSURL(string: urlString)
                
                // 显示图片
                imageView.sd_setImageWithURL(url, placeholderImage: UIImage(named: "timeline_image_placeholder"))
            }
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        // 添加控件
        contentView.addSubview(imageView)
        
        // 添加约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
    }

}